<template>
  <div class="h-full">
    <SearchCom
      :searchList="searchConfig"
      @search="handleSearch"
      @reset="handleReset"
    />
    <div class="table-container">
      <!-- 订单状态选择 -->
      <div class="status-filter">
        <el-radio-group v-model="orderStatus" @change="handleStatusChange">
          <el-radio-button label="all">全部订单</el-radio-button>
          <el-radio-button label="pending_payment">待付款</el-radio-button>
          <el-radio-button label="pending_delivery">待发货</el-radio-button>
          <el-radio-button label="pending_receipt">待收货</el-radio-button>
          <el-radio-button label="pending_review">待评价</el-radio-button>
          <el-radio-button label="completed">已完成</el-radio-button>
          <el-radio-button label="refund">退款售后</el-radio-button>
          <el-radio-button label="cancelled">已取消</el-radio-button>
        </el-radio-group>
      </div>
      
      <el-table :data="tableData" style="width: 100%" border class="cover-table">
        <el-table-column prop="orderNumber" label="订单信息" min-width="220">
          <template #default="scope">
            <div class="order-info">
              <div><strong>订单编号: </strong>{{ scope.row.orderNumber }}</div>
              <div><strong>下单时间: </strong>{{ scope.row.orderTime }}</div>
              <div><strong>订单状态: </strong>
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="商家信息" min-width="200">
          <template #default="scope">
            <div>
              <div><strong>商家ID: </strong>{{ scope.row.sellerId }}</div>
              <div><strong>商家名称: </strong>{{ scope.row.sellerName }}</div>
              <div><strong>商家地址: </strong>{{ scope.row.sellerAddress }}</div>
              <div><strong>联系人: </strong>{{ scope.row.sellerContact }}</div>
              <div><strong>联系电话: </strong>{{ scope.row.sellerPhone }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="用户信息" min-width="200">
          <template #default="scope">
            <div>
              <div><strong>用户姓名: </strong>{{ scope.row.userName }}</div>
              <div><strong>联系电话: </strong>{{ scope.row.userPhone }}</div>
              <div><strong>邮箱地址: </strong>{{ scope.row.userEmail }}</div>
              <div><strong>配送地址: </strong>{{ scope.row.deliveryAddress }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="商品信息" min-width="250">
          <template #default="scope">
            <div v-for="(item, index) in scope.row.items" :key="index" class="dish-item">
              <div class="flex">
                <div class="dish-img" :style="{backgroundImage: `url(${item.image})`}"></div>
                <div class="dish-info">
                  <div>{{ item.name }}</div>
                  <div>单价: ¥{{ item.price }} × {{ item.quantity }}</div>
                  <div>小计: ¥{{ (item.price * item.quantity).toFixed(2) }}</div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="配送信息" min-width="180">
          <template #default="scope">
            <div v-if="scope.row.deliveryStaff">
              <div><strong>配送员: </strong>{{ scope.row.deliveryStaff.name }}</div>
              <div><strong>联系电话: </strong>{{ scope.row.deliveryStaff.phone }}</div>
              <div v-if="scope.row.deliveryTime"><strong>发货时间: </strong>{{ scope.row.deliveryTime }}</div>
              <div v-if="scope.row.receivingTime"><strong>收货时间: </strong>{{ scope.row.receivingTime }}</div>
            </div>
            <div v-else>
              <span class="no-delivery">暂无配送信息</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="订单金额" min-width="180">
          <template #default="scope">
            <div>
              <div><strong>商品原价: </strong>¥{{ scope.row.originalPrice }}</div>
              <div><strong>打包费: </strong>¥{{ scope.row.packagingFee }}</div>
              <div><strong>配送费: </strong>¥{{ scope.row.deliveryFee }}</div>
              <div><strong>优惠券: </strong>-¥{{ scope.row.couponDiscount }}</div>
              <div><strong>积分抵扣: </strong>-¥{{ scope.row.pointsDiscount }}</div>
              <div class="total-amount"><strong>实付金额: </strong>¥{{ scope.row.totalAmount }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 'pending_delivery'"
              link 
              type="primary" 
              @click="handleDelivery(scope.row)"
            >
              发货
            </el-button>
            <el-button
              link
              type="primary"
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 配送员选择对话框 -->
    <el-dialog
      v-model="deliveryDialogVisible"
      title="选择配送员"
      width="500px"
    >
      <el-form :model="deliveryForm" label-width="100px">
        <el-form-item label="配送员">
          <el-select v-model="deliveryForm.staffId" placeholder="请选择配送员">
            <el-option
              v-for="staff in deliveryStaffList"
              :key="staff.id"
              :label="staff.name"
              :value="staff.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deliveryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDelivery">确认发货</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 使用独立的订单详情组件 -->
    <EditDia v-model="detailDialogVisible" :data="currentOrderDetail" />
  </div>
</template>

<script setup>
import { ref } from "vue";
import SearchCom from "@/components/SearchCom.vue";
import { ElMessage } from 'element-plus';
import EditDia from './editDia.vue';

// 搜索配置
const searchConfig = ref([
  {
    label: "订单编号",
    key: "orderNumber",
    type: "input",
  },
  {
    label: "商家ID",
    key: "sellerId",
    type: "input",
  },
  {
    label: "商家名称",
    key: "sellerName",
    type: "input",
  },
  {
    label: "联系人",
    key: "sellerContact",
    type: "input",
  },
  {
    label: "联系电话",
    key: "sellerPhone",
    type: "input",
  },
  {
    label: "用户姓名",
    key: "userName",
    type: "input",
  },
  {
    label: "用户电话",
    key: "userPhone",
    type: "input",
  },
  {
    label: "下单时间",
    key: "orderTime",
    type: "daterange",
    dateType: "daterange",
  },
  {
    label: "订单状态",
    key: "status",
    type: "select",
    options: [
      { label: "全部", value: "" },
      { label: "待付款", value: "pending_payment" },
      { label: "待发货", value: "pending_delivery" },
      { label: "待收货", value: "pending_receipt" },
      { label: "待评价", value: "pending_review" },
      { label: "已完成", value: "completed" },
      { label: "退款售后", value: "refund" },
      { label: "已取消", value: "cancelled" },
    ],
  },
]);

// 订单状态
const orderStatus = ref('all');

// 分页相关数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);

// 对话框显示状态
const deliveryDialogVisible = ref(false);
const detailDialogVisible = ref(false);

// 当前操作的订单
const currentOrder = ref(null);
const currentOrderDetail = ref(null);

// 发货表单
const deliveryForm = ref({
  staffId: '',
});

// 配送员列表（模拟数据）
const deliveryStaffList = ref([
  { id: 1, name: '配送员1', phone: '13900001111' },
  { id: 2, name: '配送员2', phone: '13900002222' },
  { id: 3, name: '配送员3', phone: '13900003333' },
  { id: 4, name: '配送员4', phone: '13900004444' },
  { id: 5, name: '配送员5', phone: '13900005555' },
]);

// 模拟表格数据
const generateMockData = () => {
  return Array.from({ length: 10 }, (_, index) => {
    const status = ['pending_payment', 'pending_delivery', 'pending_receipt', 'pending_review', 'completed', 'refund', 'cancelled'][index % 7];
    const totalItems = Math.floor(Math.random() * 3) + 1;
    const items = Array.from({ length: totalItems }, (_, itemIndex) => ({
      id: `item_${index}_${itemIndex}`,
      name: `菜品${itemIndex + 1}`,
      price: (Math.random() * 50 + 20).toFixed(2),
      quantity: Math.floor(Math.random() * 3) + 1,
      image: 'https://img-lang.55sld.com/channel1langimages/seller/goods/FazXTfI500MzGvRhxTA.jpg'
    }));
    
    const originalPrice = items.reduce((sum, item) => sum + item.price * item.quantity, 0).toFixed(2);
    const packagingFee = (Math.random() * 5 + 1).toFixed(2);
    const deliveryFee = (Math.random() * 10 + 5).toFixed(2);
    const couponDiscount = (Math.random() * 20).toFixed(2);
    const pointsDiscount = (Math.random() * 10).toFixed(2);
    const totalAmount = (parseFloat(originalPrice) + parseFloat(packagingFee) + parseFloat(deliveryFee) - parseFloat(couponDiscount) - parseFloat(pointsDiscount)).toFixed(2);
    
    return {
      id: index + 1,
      orderNumber: `ORDER${Date.now().toString().slice(-8)}${index}`,
      orderTime: `2023-${(index % 12 + 1).toString().padStart(2, '0')}-${(index % 28 + 1).toString().padStart(2, '0')} ${(index % 24).toString().padStart(2, '0')}:${(index % 60).toString().padStart(2, '0')}`,
      status,
      paymentMethod: ['微信支付', '支付宝', '银行卡'][index % 3],
      
      sellerId: `SELLER${(index % 5 + 1).toString().padStart(4, '0')}`,
      sellerName: `商家${index % 5 + 1}`,
      sellerAddress: `北京市朝阳区建国路${88 + index}号`,
      sellerContact: `联系人${index % 5 + 1}`,
      sellerPhone: `1391234${(index % 5).toString().padStart(4, '0')}`,
      
      userName: `用户${index + 1}`,
      userPhone: `1395678${index.toString().padStart(4, '0')}`,
      userEmail: `user${index + 1}@example.com`,
      deliveryAddress: `北京市海淀区中关村大街${index + 1}号科技大厦${index % 30 + 1}层`,
      
      items,
      
      deliveryStaff: status === 'pending_payment' || status === 'cancelled' ? null : {
        id: index % 5 + 1,
        name: `配送员${index % 5 + 1}`,
        phone: `1390000${(index % 5 + 1).toString().padStart(4, '0')}`
      },
      
      originalPrice,
      packagingFee,
      deliveryFee,
      couponDiscount,
      pointsDiscount,
      totalAmount,
      
      deliveryTime: ['pending_receipt', 'pending_review', 'completed'].includes(status) ? 
        `2023-${(index % 12 + 1).toString().padStart(2, '0')}-${((index % 28) + 2).toString().padStart(2, '0')} ${((index % 24) + 1).toString().padStart(2, '0')}:${(index % 60).toString().padStart(2, '0')}` : null,
      
      receivingTime: ['pending_review', 'completed'].includes(status) ?
        `2023-${(index % 12 + 1).toString().padStart(2, '0')}-${((index % 28) + 3).toString().padStart(2, '0')} ${((index % 24) + 2).toString().padStart(2, '0')}:${(index % 60).toString().padStart(2, '0')}` : null,
      
      reviewTime: status === 'completed' ?
        `2023-${(index % 12 + 1).toString().padStart(2, '0')}-${((index % 28) + 4).toString().padStart(2, '0')} ${((index % 24) + 3).toString().padStart(2, '0')}:${(index % 60).toString().padStart(2, '0')}` : null,
      
      reviewContent: status === 'completed' ? '菜品口感非常好，配送速度很快，服务态度也很好！' : null,
    };
  });
};

const tableData = ref(generateMockData());

// 处理订单状态变化
const handleStatusChange = (status) => {
  console.log('订单状态变化:', status);
  // 实际项目中应该根据状态筛选数据或重新加载数据
  if (status === 'all') {
    tableData.value = generateMockData();
  } else {
    tableData.value = generateMockData().filter(item => item.status === status);
  }
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending_payment': '待付款',
    'pending_delivery': '待发货',
    'pending_receipt': '待收货',
    'pending_review': '待评价',
    'completed': '已完成',
    'refund': '退款售后',
    'cancelled': '已取消'
  };
  return statusMap[status] || '未知状态';
};

// 获取状态标签类型
const getStatusType = (status) => {
  const typeMap = {
    'pending_payment': 'warning',
    'pending_delivery': 'primary',
    'pending_receipt': 'success',
    'pending_review': 'info',
    'completed': 'success',
    'refund': 'danger',
    'cancelled': 'info'
  };
  return typeMap[status] || '';
};

// 处理搜索
const handleSearch = (formData) => {
  console.log("搜索条件:", formData);
  // 实际项目中这里应该调用API进行搜索
  ElMessage.success('搜索请求已发送');
};

// 处理重置
const handleReset = () => {
  console.log("表单已重置");
  // 重置后可能需要重新加载初始数据
  ElMessage.info('表单已重置');
};

// 处理发货
const handleDelivery = (row) => {
  currentOrder.value = row;
  deliveryDialogVisible.value = true;
  deliveryForm.value.staffId = '';
};

// 确认发货
const confirmDelivery = () => {
  if (!deliveryForm.value.staffId) {
    ElMessage.warning('请选择配送员');
    return;
  }
  
  // 获取选中的配送员信息
  const staff = deliveryStaffList.value.find(item => item.id === deliveryForm.value.staffId);
  
  // 更新订单状态
  const index = tableData.value.findIndex(item => item.id === currentOrder.value.id);
  if (index !== -1) {
    // 更新订单状态
    tableData.value[index].status = 'pending_receipt';
    tableData.value[index].deliveryStaff = staff;
    tableData.value[index].deliveryTime = new Date().toLocaleString();
    
    ElMessage.success('订单已发货');
    deliveryDialogVisible.value = false;
  }
};

// 查看订单详情
const handleDetail = (row) => {
  currentOrderDetail.value = { ...row };
  detailDialogVisible.value = true;
};

// 处理页码变化
const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  // 这里请求对应页的数据
};

// 处理每页数量变化
const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`);
  // 这里请求对应数量的数据
};
</script>

<style scoped lang="scss">
.table-container {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
}

.status-filter {
  margin-bottom: 20px;
}

.order-info {
  div {
    margin-bottom: 5px;
  }
}

.dish-item {
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #eee;
  
  &:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
  }
}

.dish-img {
  width: 60px;
  height: 60px;
  background-size: cover;
  background-position: center;
  border-radius: 4px;
  margin-right: 10px;
}

.dish-info {
  flex: 1;
  text-align: left;
  
  div {
    margin-bottom: 3px;
  }
}

.flex {
  display: flex;
}

.total-amount {
  color: #f56c6c;
  font-weight: bold;
}

.no-delivery {
  color: #909399;
  font-style: italic;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

// 适配移动端样式
@media (max-width: 768px) {
  .el-table {
    width: 100%;
    overflow-x: auto;
  }
  
  .dish-img {
    width: 50px;
    height: 50px;
  }
}
</style>
